package com.banciyuan.bcywebview.biz.main.group.hot;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.push.Item.BasePush;
import com.banciyuan.bcywebview.base.helper.push.Item.PushError;
import com.banciyuan.bcywebview.base.helper.push.PushFactory;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.groupdetail.AddGroupActivity;
import com.banciyuan.bcywebview.biz.main.group.groupselect.GroupSelectActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

/**
 * Created by squall on 2015/8/31.
 */
public class GroupHotFragment extends BaseLazyContainerFragment implements View.OnClickListener {

    private LoadingHelper mProgressbarHelper;
    private View mProgressbarView;
    private PullToRefreshListView mRefreshLv;
    private ListView mContentLv;
    private LayoutInflater inflater;
    private RequestQueue mQueue;
    private int pagenum = 1;
    private View bottom;

    private GroupHotAdapter mAdapter;
    private boolean loading_flag = false;
    private boolean end_flag = false;
    private LinearLayout bottom_btn;

    private boolean isHotEnd;
    private boolean isGroupEnd;
    private boolean isAnswerEnd;
    private boolean isNeedAttend;

    private List<Team> tlist = new ArrayList<>();
    private List<Team> hotList = new ArrayList<>();
    private List<Team> groupList = new ArrayList<>();
    private Team needAttendTeam;
    private Team answerTeam;

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.team_fragment_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        inflater = LayoutInflater.from(getActivity());
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new LoadingHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshLv = (PullToRefreshListView) rootview.findViewById(R.id.team_refresh_lv);
        mContentLv = mRefreshLv.getRefreshableView();

        bottom = inflater.inflate(R.layout.group_new_bottem, null);
        bottom_btn = (LinearLayout) bottom.findViewById(R.id.ll_search);
        bottom_btn.setVisibility(View.GONE);
        mContentLv.addFooterView(bottom);

        mAdapter = new GroupHotAdapter(getActivity(), tlist, -1);
        mRefreshLv.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        getHotGroupContent();
        getGroupData();
        getAnswerList();
        getNeedAttend();
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!end_flag && !loading_flag) {
                    pagenum++;
                    getGroupData();
                }
            }
        });

        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                bottom_btn.setVisibility(View.GONE);
                pagenum = 1;
                isHotEnd = false;
                isGroupEnd = false;
                isAnswerEnd = false;
                isNeedAttend = false;
                loading_flag = false;
                end_flag = false;
                initData();
            }
        });

        bottom_btn.setOnClickListener(this);
    }

    private void getAnswerList() {
        String url = HttpUtils.BASE_URL + GroupApi.getZanGroups();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, "1"));
        pairs.add(new BcyPair(HttpUtils.LIMIT, "1"));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<Team> templist = gson.fromJson(result, new TypeToken<List<Team>>() {
                        }.getType());
                        if (templist != null && !templist.isEmpty()) {
                            answerTeam = templist.get(0);
                            answerTeam.setType("local_zan");
                        }
                        isAnswerEnd = true;
                        checkEnd();
                    } catch (Exception e) {
                        isAnswerEnd = true;
                        checkEnd();
                    }
                } else {
                    isAnswerEnd = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isAnswerEnd = true;
                checkEnd();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(param);
    }

    private void getNeedAttend() {
        String url = HttpUtils.BASE_URL + GroupApi.getNeedAttend();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, "1"));
        pairs.add(new BcyPair(HttpUtils.LIMIT, "1"));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<Team> templist = gson.fromJson(result, new TypeToken<List<Team>>() {
                        }.getType());
                        if (templist != null && !templist.isEmpty()) {
                            needAttendTeam = templist.get(0);
                            needAttendTeam.setType("local_need_attend");
                        }
                        isNeedAttend = true;
                        checkEnd();
                    } catch (Exception e) {
                        isNeedAttend = true;
                        checkEnd();
                    }
                } else {
                    isNeedAttend = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isNeedAttend = true;
                checkEnd();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(param);
    }


    private void getHotGroupContent() {
        String url = HttpUtils.BASE_URL + GroupApi.getHotgroupcontent();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        Gson gson = new Gson();
                        hotList = gson.fromJson(jsonObject.getJSONArray("data").toString(), new TypeToken<List<Team>>() {
                        }.getType());
                        popIllegalPushData(hotList);
                        isHotEnd = true;
                        setWorkToTag(hotList);
                        checkEnd();
                    } catch (Exception e) {
                        isHotEnd = true;
                        checkEnd();
                    }
                } else {
                    isHotEnd = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isHotEnd = true;
                checkEnd();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void popIllegalPushData(List<Team> teams) {
        List<Team> illegalBanners = new ArrayList<>();
        for (int i = 0; i < teams.size(); i++) {
            Team team = teams.get(i);
            if ("banner".equals(team.getType())) {
                BasePush basePush = PushFactory.getPush(team.getCode());
                if (basePush instanceof PushError)
                    illegalBanners.add(team);
            }
        }
        teams.removeAll(illegalBanners);
    }

    private void setGroupUi(List<Team> templist) {
        if (pagenum == 1) {
            tlist.clear();
            templist.addAll(0, hotList);
        }
        tlist.addAll(templist);
        if (pagenum != 1 && templist.isEmpty()) {
            end_flag = true;
            bottom_btn.setVisibility(View.VISIBLE);
        }
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new GroupHotAdapter(getActivity(), tlist, -1);
            mContentLv.setAdapter(mAdapter);
        }
        mProgressbarHelper.onSuccess();
        loading_flag = false;
        mRefreshLv.onRefreshComplete();
    }

    private void getGroupData() {
        loading_flag = true;
        String url = HttpUtils.BASE_URL + GroupApi.getHotAttend();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(pagenum)));
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray data = jsonObject.getJSONArray("data");
                        Gson gson = new Gson();
                        groupList = gson.fromJson(data.toString(), new TypeToken<List<Team>>() {
                        }.getType());
                        setWorkToTag(groupList);
                        isGroupEnd = true;
                        checkEnd();
                    } catch (Exception e) {
                        isGroupEnd = true;
                        checkEnd(false);
                    }
                } else {
                    isGroupEnd = true;
                    checkEnd(false);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isGroupEnd = true;
                checkEnd(false);
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(requestParam);
    }

    private void checkEnd() {
        checkEnd(true);
    }

    private void checkEnd(boolean succ) {
        if (isGroupEnd && isHotEnd && isNeedAttend && isAnswerEnd) {
            if (succ) {
                if (answerTeam != null) {
                    if (hotList.size() >= 3) {
                        hotList.add(3, answerTeam);
                    } else {
                        hotList.add(answerTeam);
                    }
                }
                if (needAttendTeam != null) {
                    if (hotList.size() >= 8) {
                        hotList.add(8, needAttendTeam);
                    } else {
                        hotList.add(needAttendTeam);
                    }
                }
                setGroupUi(groupList);
            } else {
                loading_flag = false;
                mRefreshLv.onRefreshComplete();
                mProgressbarHelper.onFailed();
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mine_send:
                gotoUtil.gotoAct(getActivity(), AddGroupActivity.class);
                break;
            case R.id.ll_search:
                gotoUtil.gotoAct(getActivity(), GroupSelectActivity.class, 0);
                break;
        }
    }

    private void setWorkToTag(List<Team> templist) {
        for (Team h : templist) {
            if (!"banner".equals(h.getType()) && !TextUtils.isEmpty(h.getWork())) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setWork(h.getWork());
                tagDetail.setWid(h.getId());
                tagDetail.setTag_name(h.getWork());
                h.getTags().add(0, tagDetail);
            }
        }
    }

    @Override
    public void selfUpdateData() {
        if (null != mRefreshLv) {
            mRefreshLv.setRefreshing();
        }
    }
}
